<?php
/**
 * Created by PhpStorm.
 * User: Se1per
 * Date: 2023/5/26
 * Time: 0:43
 */

namespace Lib\src;

trait ApiResponse
{
    protected $code;

    protected $msg;

    protected $data = null;

    protected $count = null;

    public function JsonMain(int $code, string $msg, $data = null, $count = null): array
    {
        $this->code = $code;

        $this->msg = $msg;

        $this->data = $data !== null ? $data : null;

        $this->count = $count !== null ? $count : null;

        return $this->ReturnMain();

    }

    public function ReturnMain(): array
    {
        switch ($this->code) {
            case 200000:
                $status = 'success';
                break;
            case 200001:
            case 200002:
            case 200004:
                $status = 'warning';
                break;
            default:
                $status = 'error';
                break;
        }

        return ($this->data === null ? [
            'status' => $status,
            'code' => $this->code,
            'message' => $this->msg,
        ] : (($this->count === null) ? [
            'status' => $status,
            'code' => $this->code,
            'message' => $this->msg,
            'data' => $this->data,
        ] : [
            'status' => $status,
            'code' => $this->code,
            'message' => $this->msg,
            'data' => $this->data,
            'count' => $this->count,
        ]));

    }
}